package com.hao.study.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.hao.study.common.APIResponse;
import com.hao.study.common.ResponeCode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: author
 * @description:    文件操作
 * @date: 2024/6/12 17:18
 * @version: 1.0
 */
@Api(tags={"文件上传下载管理接口"})
@RestController
@RequestMapping("/files")
public class FileController {

    @Value("${File.uploadPath}"+"/avatar/")
    private String filePath;
    @Value("${server.port}")
    private int serverPort;
@PostMapping("/upload")
public APIResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
    // 允许上传的文件类型列表
    List<String> allowedTypes = Arrays.asList(
            "image/jpeg", // JPEG
            "image/png",  // PNG
            "image/gif",  // GIF
            "image/svg", // SVG
            "image/webp" // WEBP
            );

    // 文件类型检查
    if (!allowedTypes.contains(file.getContentType())) {
        return new APIResponse<>(ResponeCode.FAIL, "不允许的文件类型");
    }

    // 文件大小检查，例如限制为10MB
    long maxSize = 10 * 1024 * 1024; // 10MB
    if (file.getSize() > maxSize) {
        return new APIResponse<>(ResponeCode.FAIL, "文件大小超过限制");
    }

    // 文件名清理，移除或替换不安全字符
    String cleanedFilename = Objects.requireNonNull(FileNameUtil.getName(file.getOriginalFilename())).replaceAll("[^a-zA-Z0-9._-]", "");
    String uniqueFilename = System.currentTimeMillis() + "_" + cleanedFilename;

    String realFilePath = filePath + uniqueFilename;
    File localFile = new File(realFilePath);

    // 确保文件夹存在
    if (!FileUtil.exist(filePath)) {
        FileUtil.mkdir(filePath);
    }

    // 文件转移
    file.transferTo(localFile);

    String url = "http://localhost:" + serverPort + "/api/files/download/" + uniqueFilename;
    return new APIResponse<>(ResponeCode.SUCCESS, "上传成功", url);
}


    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename, String.valueOf(StandardCharsets.UTF_8)));
        String realFilePath = filePath+filename;
        System.out.println("download================="+realFilePath);
        byte[] bytes = FileUtil.readBytes(realFilePath);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
    @DeleteMapping("/deleteFile")
    public APIResponse<String> deleteFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            // 提取文件名
            String filename = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);

            // 验证文件路径是否合法
            String realFilePath = filePath  + filename;
            if (!realFilePath.startsWith(filePath)) {
                return new APIResponse<>(ResponeCode.FAIL, "非法路径", null);
            }

            // 删除文件
            File file = new File(realFilePath);
            if (file.exists()) {
                if (file.delete()) {
                    return new APIResponse<>(ResponeCode.SUCCESS, "文件删除成功", null);
                } else {
                    return new APIResponse<>(ResponeCode.FAIL, "文件删除失败", null);
                }
            } else {
                return new APIResponse<>(ResponeCode.FAIL, "文件不存在", null);
            }
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, "删除文件出错", null);
        }
    }
}

